package ufr_stgi.assistance_conduite;

import java.io.File;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.Environment;
import android.preference.*;
import android.preference.Preference.OnPreferenceClickListener;
import android.util.Log;

/**
 * Gère automatiquement les préférences de l'application
 * @author Guillaume MONTAVON & Renaud DAVID (Master 2 RIM)
 */
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener, OnPreferenceClickListener {
	
	SharedPreferences pref;
	private MonApplication appli; //application
	
	/* (non-Javadoc)
	 * @see android.preference.PreferenceActivity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.prefs);
		appli = (MonApplication)getApplication();
		
		pref = getPreferenceManager().getSharedPreferences();
		pref.registerOnSharedPreferenceChangeListener(this);
		
	}
	
	/* (non-Javadoc)
	 * @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged(android.content.SharedPreferences, java.lang.String)
	 */
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		
		//lorsqu'une préférence à été modifié
		
		if(key.equals("dir_carte_sd")) {
			
			String newDest = sharedPreferences.getString(key, "");
			
			if(!appli.getDossierDest().equals("") && !newDest.equals("")) {
				File file = new File(Environment.getExternalStorageDirectory(), appli.getDossierDest());
				File file2 = new File(Environment.getExternalStorageDirectory(), newDest);
				if(!file2.exists() && file.renameTo(file2)) {
					Log.i("renommer", "renommer");
					appli.setDossierDest(newDest);
				}
				else
					Log.i("pas renommer", "pas renommer");
			}
			else
				Log.i("getDossierDest", "pas renommer");
		}
	}
	
	/* (non-Javadoc)
	 * @see android.preference.Preference.OnPreferenceClickListener#onPreferenceClick(android.preference.Preference)
	 */
	@Override
	public boolean onPreferenceClick(Preference preference) {
		return true;
	}
}